<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import {
  workClientStrategyPageSelect,
  moduleGetDetail,
  getWorkSlaSelect,
  moduleSave,
} from '@/api/basic'
import { Warning } from '@element-plus/icons-vue'
import { ElMessage, FormInstance } from 'element-plus'
import _ from 'lodash'
import { SlaRuleOptions } from './types'
import { OrderSetAPIRequestParam } from '@/typings/api/ParamSet/OrderSet'
import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'
import autoFixedDicimal from '@/utils/money'
const props = defineProps({
  mode: {
    type: String,
    default: () => 'edit',
  },
  moduleId: {
    type: String,
    required: true,
  },
})

/**
 * 使用表单验证服务
 */
const { handleFormValidate, resetFormValidateResult, getFormItemStyle } = useFormValidateService([
  { name: 'name', isSelect: false, errMarginBottom: 26 },
  { name: 'inSourcingPrice', isSelect: false },
  { name: 'outSourcingPrice', isSelect: false },
  { name: 'warrantyDay', isSelect: false },
  { name: 'collectCustomerGoodsPrice', isSelect: false },
  { name: 'callPhoneType', isSelect: false },
  { name: 'autoCheckSuspend', isSelect: false },
  { name: 'saveDataMethod', isSelect: false },
])

// 分配客服规则搜索名称
const workClientStrategyName = ref('')

// 分配客服规则下拉数据
const clientStrategyOption = ref([])

// form组件实例
const formRef = ref<FormInstance | null>(null)

// 类型下拉数据
const typeOptional = ref([
  { value: 1, label: '安装' },
  { value: 2, label: '维修' },
  { value: 3, label: '保养' },
  { value: 4, label: '其他' },
])
// 获取表单数据加载状态 - 只有编辑时才能为true
const getFormDataLoading = ref(false)

// 验证规则
const rules = ref({
  name: [{ required: true, message: '请输入模块名称', trigger: 'blur' },
  { max: 10, message: '最多10个字符', trigger: 'blur' },
  ],
  inSourcingPrice: [
    { required: true, message: '请输入保内费用', trigger: ['blur', 'change'] },
    {
      pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
      message: '仅允许输入7位整数，或输入7位整数带两位小数',
      trigger: ['blur', 'change'],
    },
  ],
  outSourcingPrice: [
    { required: true, message: '请输入保外费用', trigger: ['blur', 'change'] },
    {
      pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
      message: '仅允许输入7位整数，或输入7位整数带两位小数',
      trigger: ['blur', 'change'],
    },
  ],
  warrantyDay: [
    { required: true, message: '请输入质保天数', trigger: ['blur', 'change'] },
    {
      pattern: /^0$|^[1-9]{1}\d{0,5}$/g,
      message: '质保天数输入错误，请输入 >=0 的六位整数',
      trigger: ['blur', 'change'],
    },
  ],
  collectCustomerGoodsPrice: [{ required: true, message: '请输入商品单价', trigger: ['blur', 'change'] },
  {
    pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
    message: '仅允许输入7位整数，或输入7位整数带两位小数',
    trigger: ['blur', 'change'],
  },],
  callPhoneType: [
    { required: true, message: '请选择拨打电话类型', trigger: ['blur', 'change'] },
    {
      pattern: /^[01]/g,
      message: '请选择拨打电话类型',
      trigger: ['blur', 'change'],
    },
  ],
  autoCheckSuspend: [{ required: true, message: '请选择挂起审核', trigger: ['blur', 'change'] }],
  saveDataMethod: [{ required: true, message: '请选择工单挂起', trigger: ['blur', 'change'] }],
})

// 表单数据
const form = ref<OrderSetAPIRequestParam.AddOrUpdateOrderModule>({
  id: '',
  name: '',
  enableWarrantyOrder: true,
  overinsured: false, // 质保状态，是否保外：false-保内，true-保外
  inSourcingPrice: 0, // 保内费用
  outSourcingPrice: 0, // 保外费用
  status: false,
  reservationTimeType: 2, // 预约时间类型：1-不启用，2-24小时，3-预约时间范围
  reservationStartTime: '', // 预约开始时间，仅传小时
  reservationEndTime: '', // 预约结束时间，仅传小时
  type: 1,
  warrantyDay: 30,
  autoDispatchClient: true, // 	是否自动分配客服：false-否，true-是
  workClientStrategyId: '', // 工单客服分派策略ID
  autoDispatchNetwork: true, // 	是否自动分配服务商：false-否，true-是
  mobileCreateOrderShow: true, // 是否移动报单端展示：false-不显示，true-显示
  enableStatementVerifCode: true, //是否启用结单核销码：false-不启用，true-启用,示例值(true)
  statementVerifCodeType: 1, //结单核销码类型：1-随机，2-固定；当enableStatementVerifCode=true时生效,示例值(1)
  enableSign: true, // 是否开启签到
  signType: 1, // 签到方式：1-定位签到，2-拍照签到
  enableSecurityWatermark: true, // 是否启用拍照防伪作弊水印：false-关闭，true-开启
  signRange: 50, // 签到范围，单位：米
  callPhoneType: 1, // 拨打电话类型：0-关闭，1-必须拨打
  enableSuspend: true, // 是否启用挂起工单：false-关闭，true-开启
  autoCheckSuspend: true, // 是否自动挂起审核通过：false-人工审核，true-自动审核通过
  workSlaId: '', // 工单Sla规则ID
  signRangeType: 1,
  collectCustomerGoodsPrice: 0//收货客户商品单价
})

// 初始化表单
const initForm = () => {
  form.value.id = props.mode === 'edit' ? props.moduleId : ''
  form.value.name = ''
  form.value.enableWarrantyOrder = true
  form.value.overinsured = false // 质保状态，是否保外：false-保内，true-保外
  form.value.inSourcingPrice = 0 // 保内费用
  form.value.outSourcingPrice = 0 // 保外费用
  form.value.status = false
  form.value.reservationTimeType = 2 // 预约时间类型：1-不启用，2-24小时，3-预约时间范围
  form.value.reservationStartTime = '' // 预约开始时间，仅传小时
  form.value.reservationEndTime = '' // 预约结束时间，仅传小时
  form.value.type = 1
  form.value.warrantyDay = 30
  form.value.autoDispatchClient = true // 	是否自动分配客服：false-否，true-是
  form.value.workClientStrategyId = '' // 工单客服分派策略ID
  form.value.autoDispatchNetwork = true // 	是否自动分配服务商：false-否，true-是
  form.value.mobileCreateOrderShow = true
  form.value.enableStatementVerifCode = true //是否启用结单核销码
  form.value.statementVerifCodeType = 1 //结单核销码类型
  form.value.enableSign = true // 是否开启签到
  form.value.signType = 1 // 签到方式：1-定位签到，2-拍照签到
  form.value.enableStatementVerifCode = true // 是否启用拍照防伪作弊水印：false-关闭，true-开启
  form.value.signRange = 50// 签到范围，单位：米
  form.value.callPhoneType = 1 // 拨打电话类型：0-关闭，1-必须拨打
  form.value.enableSuspend = true // 是否启用挂起工单：false-关闭，true-开启
  form.value.autoCheckSuspend = true // 是否自动挂起审核通过：false-人工审核，true-自动审核通过
  form.value.workSlaId = '' // 工单Sla规则ID
  form.value.signRangeType = 1
  form.value.collectCustomerGoodsPrice = 0
}

// 获取分配客服规则下拉选项加载
const getClientStrategyOptionLoading = ref(false)

// 获取分配客服规则Api
const clientStrategyApi = async () => {
  getClientStrategyOptionLoading.value = true
  const searchData = {
    limit: 50,
    name: workClientStrategyName.value,
    page: 1,
  }
  const res = await workClientStrategyPageSelect(searchData)
  clientStrategyOption.value = res.data.data.rows
  getClientStrategyOptionLoading.value = false
}

// 客服分配规则远程搜索
const workClientStrategyRemoteMethod = _.throttle((name: string) => {
  if (workClientStrategyName.value !== name) {
    workClientStrategyName.value = name
    clientStrategyApi()
  }
}, 500)

// 获取sla规则下拉选项关键字
const getSlaRuleOptionsKeyword = ref('')

// 获取sla规则下拉选项加载
const getSlaRuleOptionsLoading = ref(false)

// sla规格下拉选项
const slaRuleOptions = ref<Array<SlaRuleOptions>>([])

/**
 * 获取SLA下拉选项
 */
const handleGetSlaRuleOptions = _.throttle((query: string) => {
  if (getSlaRuleOptionsKeyword.value !== query) {
    getSlaRuleOptionsKeyword.value = query
    getSlaRuleOptionsFn(getSlaRuleOptionsKeyword.value)
  }
}, 500)

/**
 * 获取sla规则下拉选项犯法
 * @param {string} query - 关键字
 */
const getSlaRuleOptionsFn = async (query: string) => {
  getSlaRuleOptionsLoading.value = true
  const param = {
    name: query,
    limit: 0,
    page: 0,
  }

  const res = await getWorkSlaSelect(param)
  slaRuleOptions.value = res.data.data.rows
  getSlaRuleOptionsLoading.value = false
}

// 保存加载
const saveLoading = ref(false)

/**
 * 保存方法
 */
const save = async () => {
  if (!formRef.value) {
    return false
  }
  if (
    form.value.reservationTimeType == 3 &&
    (!form.value.reservationStartTime || !form.value.reservationEndTime)
  ) {
    ElMessage({
      message: '预约时间范围不能为空',
      type: 'warning',
      duration: 2000,
    })
    return
  }
  saveLoading.value = true
  try {
    await formRef.value.validate()
    const res = await moduleSave(form.value)
    if (res.data.isError)
      ElMessage({
        type: res.data.success ? 'success' : 'error',
        message: res.data.message,
      })
    return res.data.success
  } catch (e) {
    // 校验失败
  }
  saveLoading.value = false
}

onMounted(async () => {
  initForm()
  await clientStrategyApi()
  if (props.mode === 'edit') {
    getFormDataLoading.value = true
    const res = await moduleGetDetail(props.moduleId)
    getFormDataLoading.value = false
    Object.assign(form.value, res.data.data.row)
    if (form.value.reservationEndTime === null) {
      form.value.reservationEndTime = ''
    }
    if (form.value.workClientStrategyId == 0) {
      form.value.workClientStrategyId = ''
    }
  }
})

defineExpose({
  form,
  initForm,
  save,
  getSlaRuleOptionsFn,
})
</script>

<template>
  <el-form label-width="110" ref="formRef" :rules="rules" :model="form" @validate="handleFormValidate">
    <div v-loading="getFormDataLoading" style="display: grid; grid-template-columns: repeat(2, 1fr)">
      <div>
        <!-- 模块类型 -->
        <el-form-item label="模块类型" required style="margin-bottom: 12px">
          <el-select size="large" placeholder="请选择" v-model="form.type">
            <el-option v-for="item in typeOptional" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 模块名称 -->
        <el-form-item label="模块名称" :style="getFormItemStyle['name']" prop="name">
          <el-input v-model="form.name" clearable placeholder="请输入名称" />
        </el-form-item>

        <!-- 质保状态 -->
        <el-form-item label="质保状态" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group v-model="form.overinsured" class="three_radio">
            <el-radio :value="false">
              <span class="bg_text">在保</span>
            </el-radio>
            <el-radio style="opacity: 0" :value="false">
              <span></span>
            </el-radio>
            <el-radio :value="true">
              <span class="bg_text">过保</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 工单质保 -->
        <el-form-item label="工单质保" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group v-model="form.enableWarrantyOrder" class="three_radio">
            <el-radio :value="true">
              <span class="bg_text">启用</span>
            </el-radio>
            <el-radio style="opacity: 0" :value="false">
              <span></span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">禁用</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 质保周期 -->
        <el-form-item label="质保周期" :style="getFormItemStyle['warrantyDay']" prop="warrantyDay">
          <el-input v-model="form.warrantyDay" maxlength="6" clearable placeholder="请输入天数" />
        </el-form-item>

        <!-- 保内费用 -->
        <el-form-item label="保内费用" class="form-item" :style="getFormItemStyle['inSourcingPrice']"
          prop="inSourcingPrice">
          <el-input v-model="form.inSourcingPrice" clearable maxlength="10" placeholder="请输入保存费用" />
        </el-form-item>

        <!-- 保外费用 -->
        <el-form-item label="保外费用" :style="getFormItemStyle['outSourcingPrice']" prop="outSourcingPrice">
          <el-input v-model="form.outSourcingPrice" clearable maxlength="10" placeholder="请输入保外费用" />
        </el-form-item>
        <!-- 收货客户商品单价-->
        <el-form-item label="商品单价" :style="getFormItemStyle['collectCustomerGoodsPrice']"
          prop="collectCustomerGoodsPrice">
          <el-input v-model="form.collectCustomerGoodsPrice" maxlength="10" clearable placeholder="请输入天数" />
        </el-form-item>
        <!-- SLA规则 -->
        <el-form-item label="SLA规则" class="form_item" style="margin-bottom: 14px" prop="slaRule">
          <el-select placeholder="请选择" filterable clearable :filter-method="handleGetSlaRuleOptions"
            :loading="getSlaRuleOptionsLoading" v-model="form.workSlaId">
            <el-option v-for="(slaRule, slaRuleIndex) in slaRuleOptions" :key="slaRuleIndex" :label="slaRule.name"
              :value="slaRule.id" />
          </el-select>
        </el-form-item>

        <!--拨打电话类型-->
        <el-form-item required prop="callPhoneType" label="拨打电话" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group v-model="form.callPhoneType" class="el-group">
            <el-radio :value="0">
              <span class="bg_text">关闭</span>
            </el-radio>
            <el-radio :value="1">
              <div style="display: flex;align-items: center;gap: 6px;"><span class="bg_text">必须拨打</span><el-tooltip
                  effect="dark" content="开启后，工单必须拨打电话才能操作" placement="top">
                  <el-icon size="16" color="#000">
                    <Warning />
                  </el-icon>
                </el-tooltip></div>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 预约时间 -->
        <el-form-item label="预约时间" class="form_radio_item" style="margin-bottom: 14px" prop="reservationTimeType">
          <el-radio-group v-model="form.reservationTimeType" class="three_radio">
            <el-radio :value="1">
              <span class="bg_text">不启用</span>
            </el-radio>
            <el-radio :value="2">
              <span class="bg_text">24小时</span>
            </el-radio>
            <el-radio :value="3">
              <span class="bg_text">预约时间范围</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 预约时间范围 -->
        <el-form-item label="预约时间范围" v-if="form.reservationTimeType === 3" style="margin-bottom: 14px">
          <div style="display: flex; gap: 5px; width: 100%">
            <el-time-select class="reservationTime-el-time-select" v-model="form.reservationStartTime"
              :max-time="form.reservationEndTime" placeholder="预约开始时间" step="3:00" start="05:00" end="23:00"
              size="small" :disabled="form.reservationTimeType !== 3" />
            <span class="reservationTime-span">~</span>
            <el-time-select class="reservationTime-el-time-select" v-model="form.reservationEndTime"
              :min-time="form.reservationStartTime" placeholder="预约结束时间" step="3:00" start="05:00" end="23:00"
              size="small" :disabled="form.reservationTimeType !== 3" />
          </div>
        </el-form-item>

        <!-- 移动端可见 -->
        <el-form-item label="移动端可见" class="form_radio_item">
          <el-radio-group v-model="form.mobileCreateOrderShow" class="three_radio">
            <el-radio :value="true">
              <span class="bg_text">显示</span>
            </el-radio>
            <el-radio :value="false">
              隐藏
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div>
        <!-- 分配客服 -->
        <el-form-item label="分配客服" class="form_radio_item" prop="autoDispatchClient" style="margin-bottom: 14px">
          <el-radio-group v-model="form.autoDispatchClient">
            <el-radio :value="false">
              <span class="bg_text">人工分配</span>
            </el-radio>
            <el-radio :value="true">
              <span class="bg_text">自动分配</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 分配客服规则 -->
        <el-form-item label="分配规则" class="form-item" style="margin-bottom: 12px">
          <el-select :disabled="!form.autoDispatchClient" v-model="form.workClientStrategyId" placeholder="请选择分配规则"
            filterable :filter-method="workClientStrategyRemoteMethod" clearable
            :loading="getClientStrategyOptionLoading">
            <el-option v-for="item in clientStrategyOption" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- 分派服务商 -->
        <!-- <el-form-item label="分派服务商" class="form_radio_item" prop="autoDispatchNetwork" style="margin-bottom: 14px">
          <el-radio-group v-model="form.autoDispatchNetwork">
            <el-radio :value="false">
              <span class="bg_text">人工派单</span>
            </el-radio>
            <el-radio :value="true">
              <span class="bg_text">自动派单</span>
            </el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- 分派规则 -->
        <!-- 后面有需要再添加 -->
        <!-- <el-form-item label="分派规则" class="form-item" prop="autoDispatchNetwork">
          <el-select>
            <el-option>请选择</el-option>
          </el-select>
        </el-form-item> -->

        <!-- 结单核销码 - 启用/禁用 -->
        <el-form-item label="结单核销码" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group v-model="form.enableStatementVerifCode">
            <el-radio :value="true">
              <span class="bg_text">启用</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">禁用</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 核销码内容 -->
        <el-form-item label="核销码内容" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group :disabled="!form.enableStatementVerifCode" v-model="form.statementVerifCodeType">
            <el-radio :value="1">
              <div style="display: flex; align-items: center; gap: 5px">
                <span class="bg_text">随机</span>
                <el-tooltip effect="dark" content="每单随机生成不同的核销码" placement="top">
                  <el-icon size="16" color="#000">
                    <Warning />
                  </el-icon>
                </el-tooltip>
              </div>
            </el-radio>
            <el-radio :value="2">
              <div style="display: flex; align-items: center; gap: 5px">
                <span class="bg_text">固定</span>
                <el-tooltip effect="dark" content="每单生成固定的核销码" placement="top">
                  <el-icon size="16" color="#000">
                    <Warning />
                  </el-icon>
                </el-tooltip>
              </div>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 开启签到 -->
        <el-form-item label="开启签到" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group v-model="form.enableSign">
            <el-radio :value="true">
              <span class="bg_text">启用</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">关闭</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 签到方式 -->
        <el-form-item label="签到方式" class="form_radio_item" style="margin-bottom: 14px">
          <el-radio-group :disabled="!form.enableSign" v-model="form.signType">
            <el-radio :value="1">
              <span class="bg_text">定位签到</span>
            </el-radio>
            <el-radio :value="2">
              <span class="bg_text">拍照签到</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 防作弊水印 -->
        <el-form-item label="防作弊水印" class="form_radio_item" style="margin-bottom: 12px">
          <el-radio-group :disabled="form.signType !== 2 || !form.enableSign" v-model="form.enableSecurityWatermark">
            <el-radio :value="true">
              <span class="bg_text">启用</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">关闭</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 签到范围限制 -->
        <el-form-item label="签到范围限制" class="form_radio_item" style="margin-bottom: 12px">
          <el-radio-group :disabled="form.signType !== 1 || !form.enableSign" v-model="form.signRangeType">
            <el-radio :value="1">
              <span class="bg_text">有限制</span>
            </el-radio>
            <el-radio :value="2">
              <span class="bg_text">不限制</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 签到范围 -->
        <el-form-item label="签到范围" class="form-item">
          <div style="display: flex;flex-wrap: nowrap;align-items: center;width: 100%;">
            <el-input :disabled="form.signType !== 1 || !form.enableSign || form.signRangeType == 2"
              v-model="form.signRange" style="width: 100%;" placeholder="输入范围：米" autoFixedDicimal
              @input="form.signRange = autoFixedDicimal(form.signRange, 0)"
              @change="form.signRange = Number(form.signRange)" maxlength="8">
              <template #append><span style="font-size: 12px">米</span> </template></el-input>
            &nbsp;&nbsp;<el-tooltip effect="dark" content="定位必须在签到地址范围内多少米" placement="top">
              <el-icon size="16" color="#000">
                <Warning />
              </el-icon>
            </el-tooltip>
          </div>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" class="form_item" style="margin-bottom: 12px">
          <el-radio-group v-model="form.status">
            <el-radio :value="false">
              <span class="bg_text">启用</span>
            </el-radio>
            <el-radio :value="true">
              <span class="bg_text">禁用</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!--工单挂起-->
        <el-form-item label="工单挂起" required prop="enableSuspend" style="margin-bottom: 12px">
          <div style="display: flex; align-items: center; gap: 5px">
            <el-switch v-model="form.enableSuspend" />
            <span v-if="form.enableSuspend">启用</span>
            <span v-else>关闭</span>
          </div>
        </el-form-item>

        <!--挂起审核-->
        <el-form-item label="挂起审核" required class="form_radio_item" prop="autoCheckSuspend">
          <el-radio-group v-model="form.autoCheckSuspend">
            <el-radio :value="true">
              <span class="bg_text">无需审核</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">需要审核</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </div>
  </el-form>
</template>

<style scoped lang="scss">
:deep(.el-radio__input.is-disabled) {
  span {
    background: #f5f7fa !important;
    border-color: #e4e7ed !important;
  }

  span.el-radio__label {
    span {
      color: #999 !important;
    }
  }
}

:deep(.el-radio.is-disabled.is-checked) {
  span.el-radio__label {
    span {
      color: #999 !important;
    }
  }
}
</style>
<style>
.el-form-item__content .el-input-group {
  height: 28px !important;
}
</style>
